<template>
  <div>
    <div>
      <div>
        <el-row style="padding-top:10px">
          <el-col :span="6" style="padding-right:10px">
            <el-select v-model="queryData.enable">
              <el-option value="true" label="启用" />
              <el-option value="false" label="停用" />
            </el-select>
          </el-col>
          <el-col :span="6" style="padding-right:10px">
            <el-button type="primary" @click="list">搜索</el-button>
          </el-col>
        </el-row>

      </div>
      <el-divider />
      <div style="text-align: right;">
        <el-button v-has="50101" type="primary" @click="add">新增</el-button>
      </div>
      <el-divider />
      <el-table :data="table_body" stripe style="width: 100%">
        <el-table-column prop="channelCode" label="渠道代码" />
        <el-table-column prop="channelName" label="渠道名称" />
        <el-table-column prop="enable" label="状态">
          <template slot-scope="scope">
            <div v-if="scope.row.enable">启用</div>
            <div v-else>停用</div>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作者" />
        <el-table-column prop="createAt" label="创建时间" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-has="50102" size="small" shape="circle" type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.enable" v-has="50103" size="small" shape="circle" type="text" @click="disabled(scope.row)">停用</el-button>
            <el-button v-else v-has="50104" size="small" shape="circle" type="text" @click="enable(scope.row)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background :current-page="queryData.currentPage" :page-sizes="[50,100]" :page-size="queryData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal" style="float:right;" @size-change="onPageSizeChange" @current-change="onPageChange" />

    </div>
    <div>
      <el-dialog :visible.sync="openDrawer" :title="drawerTitle" width="60%" top="0" :close-on-click-modal="false">
        <el-form :model="formData">
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="渠道代码" label-position="top" required>
                <el-input v-model="formData.channelCode" placeholder="渠道代码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="渠道名称" label-position="top" required>
                <el-input v-model="formData.channelName" placeholder="渠道中文名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="是否启用" label-position="top" required>
                <el-select v-model="formData.enable" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目的地国家" label-position="top" required>
                <el-select v-model="formData.country" :filterable="true" style="width:100%;">
                  <el-option v-for="item in countrys" :key="item.code" :value="item.code" :label="item.nameCn" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="渠道类型" label-position="top" required>
                <el-select v-model="formData.channelType" placeholder="请选渠道类型" style="width:100%;">
                  <el-option v-for="item in channelTypes" :key="item.value" :value="item.value" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="佣金科目" label-position="top">
                <el-select v-model="formData.commissionChargeSubjectId" clearable filterable style="width:100%;" placeholder="如果没有可选项,请先新建费用科目">
                  <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="供应商" label-position="top" required>
                <el-select v-model="formData.supplier" :label-in-value="true" placeholder="供应商" style="width:100%;" @change="supplierOptionChange">
                  <el-option v-for="item in supplierOptions" :key="item.supplier" :value="item.supplier" :label="item.supplier" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="API配置" label-position="top" required>
                <el-select v-model="formData.providerConfigId" placeholder="API配置" style="width:100%;" @change="providerConfigOptionChange">
                  <el-option v-for="item in providerConfigOptions" :key="item.id" :value="item.id" :label="item.shortName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="供应商产品" label-position="top" required>
                <el-select v-model="formData.supplierChannelCode" placeholder="请选供应商产品" style="width:100%;">
                  <el-option v-for="(option, index) in supplierChannelCode" :key="index" :value="option.code" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账单供应商名称" label-position="top" required>
                <el-select v-model="formData.invoiceSupplierId" placeholder="请选账单供应商" style="width:100%;">
                  <el-option v-for="(option, index) in invoiceSupplierOptions" :key="index" :value="option.id" :label="option.clientName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="计泡方式" label-position="top" required>
                <el-select v-model="formData.billedWeightCalculationMethodType" placeholder="请选计泡方式" style="width:100%;">
                  <el-option v-for="(option, index) in BilledWeightCalculationMethodTypes" :key="index" :value="option.code" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="体积重计算比率" label-position="top">
                <el-input v-model="formData.volumeWeightRadio" type="number" placeholder="体积重计算比率" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="重量单位" label-position="top" required>
                <el-select v-model="formData.weightUnit" placeholder="重量单位" style="width:100%;">
                  <el-option value="KG" label="KG" />
                  <el-option value="POUNDS" label="POUNDS" />
                  <el-option value="OZ" label="OZ" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="佣金比率" label-position="top">
                <el-input v-model="formData.commission" type="number" placeholder="佣金比率" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="单箱最小重量(KG)" label-position="top">
                <el-input v-model="formData.cartonMinWeight" type="number" placeholder="单箱最小重量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="整票最小重(KG)" label-position="top">
                <el-input v-model="formData.minTotalWeight" type="number" placeholder="整货最小重" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="单箱最低费用" label-position="top">
                <el-input v-model="formData.minChargePerCarton" type="number" placeholder="单箱最低费用" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="整票最低费用" label-position="top">
                <el-input v-model="formData.minChargePerOrder" type="number" placeholder="整票最低费用" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="是否按单箱计费" label-position="top" required>
                <el-select v-model="formData.chargingByCarton" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否实时扣费" label-position="top" required>
                <el-select v-model="formData.realTimeTransaction" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="是否用供应商成本做应收" label-position="top" required>
                <el-select v-model="formData.chargingBySupplierCost" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单约束" label-position="top">
                <el-select v-model="formData.limiters" multiple style="width:100%;">
                  <el-option v-for="(option, index) in limiterOptions" :key="index" :value="option.id" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row v-show="formData.chargingBySupplierCost == 'false'" :gutter="32">
            <el-col :span="12">
              <el-form-item label="销售价" label-position="top" required>
                <i class="el-icon-plus" style="cursor: pointer" @click="openDefDrawer" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-table v-show="formData.chargingBySupplierCost == 'false'" :data="chargeDefinitionsForEdit" stripe style="width: 100%">
          <el-table-column prop="effectiveFrom" label="生效开始日期" />
          <el-table-column prop="effectiveTo" label="生效结束日期" />
          <el-table-column prop="effective" label="当前生效中">
            <template slot-scope="scope">
              <div v-if="scope.row.effective">
                生效中
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="text" shape="circle" @click="priceEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button style="margin-right: 8px" @click="openDrawer = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <New ref="channelNew" @query="list" />
  </div>
</template>
<script>
import request from '@/utils/request'
import New from './new'
import { mapState } from 'vuex'
import { copyProperty, copyAllProperty } from '@/utils/tools'
export default {
  components: {
    New
  },
  data() {
    return {
      openChargeDefDrawer: false,
      openDrawer: false,
      country: [],
      tempIdSeq: 0,
      vars: [

      ],
      table_body: [

      ],
      price_table_body: [

      ],
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      channelTypes: [
        { 'value': 'UPS', 'name': 'UPS' },
        { 'value': 'FEDEX', 'name': 'FEDEX' },
        { 'value': 'USPS', 'name': 'USPS' },
        { 'value': 'DPD', 'name': 'DPD' },
        { 'value': 'TNT', 'name': 'TNT' },
        { 'value': 'SAGAWA', 'name': '佐川' },
        { 'value': 'DHL', 'name': 'DHL' },
        { 'value': 'TRUCK', 'name': 'TRUCK' }
      ],
      formDataDefault: {
        enable: 'true',
        channelCode: '',
        channelName: '',
        currency: '',
        channelType: '',
        supplierChannelCode: '',
        providerId: '',
        providerConfigId: '',
        supplier: '',
        country: '',
        billedWeightCalculationMethodType: null,
        weightUnit: 'KG',
        minChargePerOrder: 0,
        minChargePerCarton: 0,
        minTotalWeight: 0,
        cartonMinWeight: 0,
        volumeWeightRadio: 6000,
        commission: 0,
        chargingByCarton: 'false',
        realTimeTransaction: 'true', // 实时交易
        chargeDefinition: [],
        commissionChargeSubjectId: '',
        chargingBySupplierCost: 'false',
        invoiceSupplierId: '',
        limiters: []
      },
      formData: {
        enable: 'true',
        channelCode: '',
        channelName: '',
        country: '',
        channelType: '',
        supplierChannelCode: '',
        providerId: '',
        providerConfigId: '',
        supplier: '',
        billedWeightCalculationMethodType: null,
        weightUnit: 'KG',
        minChargePerOrder: 0,
        minChargePerCarton: 0,
        minTotalWeight: 0,
        cartonMinWeight: 0,
        volumeWeightRadio: 6000,
        commission: 0,
        chargingByCarton: 'false',
        realTimeTransaction: 'true', // 实时交易
        chargeDefinition: [],
        commissionChargeSubjectId: '',
        chargingBySupplierCost: 'false',
        invoiceSupplierId: '',
        limiters: []
      },
      chargeDefinitionsForEdit: [],
      chargeDefinitionsInitDataDefault: {
        id: '',
        currency: 'CNY',
        effectiveFrom: '',
        effectiveTo: '',
        mainCharge: {
          name: '',
          cal: 'JS',
          formula: '',
          logisticPrice: {
            minBillableWeight: '',
            selectedAreaCode: '',
            weightUnit: 'KG',
            areas: [],
            prices: {}
          }
        },
        costCharge: {
          name: 'costCharge',
          formula: ''
        },
        additionalCharges: [],
        userDefinedVariables: [],
        editing: false
      },
      chargeDefinitionsInitData: {
        id: '',
        tempId: 0,
        currency: 'CNY',
        effectiveFrom: '',
        effectiveTo: '',
        mainCharge: {
          name: '',
          cal: 'JS',
          formula: '',
          logisticPrice: {
            minBillableWeight: '',
            selectedAreaCode: '',
            weightUnit: 'KG',
            areas: [],
            prices: {}
          }
        },
        costCharge: {
          name: 'costCharge',
          formula: ''
        },
        additionalCharges: [],
        userDefinedVariables: [],
        editing: false
      },
      queryData: {
        pageSize: 50,
        currentPage: 0,
        enable: 'true'
      },
      pageTotal: 0,
      pageSizeOpts: [50, 100],
      drawerTitle: '新增',
      BilledWeightCalculationMethodTypes: [
        { code: 'ACTUALLY_WEIGHT', name: '实重' },
        { code: 'NOT_BUBBLE', name: '不计泡' },
        { code: 'HALF_BUBBLE', name: '半泡' },
        { code: 'ONE_THIRD_BUBBLE', name: '1/3泡运' },
        { code: 'VOLUME', name: '体积(m³)' },
        { code: 'THREE_TENTHS_BUBBLE', name: '3/10泡' }
      ],
      supplierOptions: [],
      supplierOptionMap: new Map(),
      providerConfigOptions: [],
      supplierChannelCode: [],
      chargeSubjectOptions: [],
      invoiceSupplierOptions: [],
      limiterOptions: []
    }
  },
  created() {
    this.list()
    this.countrys()
    this.loadVariable()
    this.loadSupplierOptions()
    this.loadChargeSubjectOptions()
    this.loadInvoiceSupplierOptions()
    this.loadLimiterOptions()
  },
  mounted() {
  },
  methods: {
    list() {
      request({
        url: 'product/query',
        data: this.queryData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.table_body = res.data.records
            this.pageTotal = res.data.total
          } else {
            this.pageTotal = 0
          }
        }
      })
    },
    supplierOptionChange(value) {
      if (!value) {
        return
      }
      const supplierOptionChange = value.label || value
      this.providerConfigOptions = this.supplierOptionMap.get(supplierOptionChange).configOptions
      this.formData.providerId = this.supplierOptionMap.get(supplierOptionChange).providerId
      if (!value.fromEdit) {
        this.formData.supplierChannelCode = ''
        this.formData.providerConfigId = ''
      }

      if (this.providerConfigOptions.length === 1) {
        this.formData.providerConfigId = this.providerConfigOptions[0].id
        this.providerConfigOptionChange({ value: this.formData.providerConfigId })
      }
    },
    providerConfigOptionChange(value) {
      if (!value) {
        return
      }
      this.loadSupplierChannelOptions()
    },
    loadVariable() {
      request({
        url: 'product/price/variable',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.vars = res.data
          }
        }
      })
    },
    loadSupplierOptions() {
      request({
        url: 'channel-provider/supplier-option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.supplierOptions = res.data
            res.data.forEach(ele => {
              this.supplierOptionMap.set(ele.supplier, ele)
            })
          }
        }
      })
    },
    loadSupplierChannelOptions() {
      request({
        url: 'channel-provider/channel-option?providerId=' + this.formData.providerId + '&providerConfigId=' + this.formData.providerConfigId,
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.supplierChannelCode = res.data
          } else {
            this.supplierChannelCode = []
            this.formData.supplierChannelCode = ''
          }
        }
      })
    },
    loadChargeSubjectOptions() {
      request({
        url: 'charge-subject/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.chargeSubjectOptions = res.data
          }
        }
      })
    },
    loadInvoiceSupplierOptions() {
      request({
        url: 'supplier/get',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.invoiceSupplierOptions = res.data
          }
        }
      })
    },
    loadLimiterOptions() {
      request({
        url: 'product/limiter/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.limiterOptions = res.data
          }
        }
      })
    },
    countrys() {
      request({
        url: '/countrys',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.countrys = res.data
          }
        }
      })
    },
    submit() {
      request({
        url: 'product/price/base/add',
        method: 'post',
        data: this.formData
      }).then(res => {
        if (res.success) {
          this.openDrawer = false
          this.list()
          this.$store.dispatch('getChannelOptions')
        }
      })
    },
    loadBasePrice(productId) {
      request({
        url: 'product/price/base?productId=' + productId,
        method: 'GET'
      }).then(res => {
        if (res.success) {
          this.chargeDefinitionsForEdit = res.data
        }
      })
    },
    edit(row) {
      this.loadBasePrice(row.id)
      this.drawerTitle = '编辑'
      this.formData.id = row.id
      copyAllProperty(this.formData, row, false)
      this.formData.chargeDefinition = []
      this.supplierOptionChange({ label: row.supplier, fromEdit: true })
      this.loadSupplierChannelOptions()
      this.openDrawer = true
      this.tempIdSeq = 0
    },
    priceEdit(row) {
      if (!row.hasOwnProperty('tempId')) {
       row.tempId = this.tempIdSeq++
      }
      copyAllProperty(this.chargeDefinitionsInitData, row, true)
      this.chargeDefinitionsInitData.editing = true
      this.openChargeDefDrawer = true
    },
    add() {
      this.$refs.channelNew.add()
    },
    openDefDrawer() {
      copyProperty(this.chargeDefinitionsInitData, this.chargeDefinitionsInitDataDefault)
      this.chargeDefinitionsInitData.editing = false
      this.chargeDefinitionsInitData.tempId = this.tempIdSeq++
      this.openChargeDefDrawer = true
    },
    closeDefDrawer() {
      this.openChargeDefDrawer = false
    },
    disabled(row) {
      request({
        url: 'product/disabled?id=' + row.id,
        method: 'GET'
      }).then(res => {
        if (res.success) {
          this.list()
        }
      })
    },
    enable(row) {
      request({
        url: 'product/enable?id=' + row.id,
        method: 'GET'
      }).then(res => {
        if (res.success) {
          this.list()
        }
      })
    },
    onPageSizeChange(pageSize) {
      this.queryData.pageSize = pageSize
      this.list()
    },
    onPageChange(page) {
      this.queryData.currentPage = page
      this.list()
    },
    chargeDefCallBack(def) {
      const defStr = JSON.stringify(def)
      const defClone = JSON.parse(defStr)
      this.openChargeDefDrawer = false
      if (this.formData.chargeDefinition[defClone.tempId]) {
        this.formData.chargeDefinition[defClone.tempId] = defClone
      } else {
        this.formData.chargeDefinition.push(defClone)
      }
      if (!def.editing || def.editing === 'true') {
        if (this.chargeDefinitionsForEdit[defClone.tempId]) {
          this.chargeDefinitionsForEdit[defClone.tempId] = defClone
        } else {
          this.chargeDefinitionsForEdit.push(defClone)
        }
      }
    }

  },
  computed: {
    pageSize() {
      return this.pageSizeOpts[0]
    },

    ...mapState(//
      {
        customerType: state => state.base.customerType, //
        paymentTerm: state => state.base.paymentTerm,
        customerOptions: state => state.base.customerOptions
      }
    )
  }
}
</script>
